/**
 * 
 */
package org.hotpotmaterial.codegenn2.utils;

import java.security.MessageDigest;
import java.util.Random;

import lombok.extern.slf4j.Slf4j;

/**
 * @author cakydeveloper
 *
 */
@Slf4j
public class MD5Util {

	/**
	 * 简单md5
	 * 
	 * @param content
	 * @return
	 */
	public static String encrypt(String content) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte strTemp[] = content.getBytes("UTF-8");
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte md[] = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 15];
				str[k++] = hexDigits[byte0 & 15];
			}

			return new String(str);
		} catch (Exception e) {
			log.error("MD5 encrypting failed!!!", e);
			return null;
		}
	}

	/**
	 * 随机盐
	 * @return
	 */
	public static String salt() {
		// 生成一个16位的随机数
		Random random = new Random();
		StringBuilder sBuilder = new StringBuilder(16);
		sBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
		int len = sBuilder.length();
		if (len < 16) {
			for (int i = 0; i < 16 - len; i++) {
				sBuilder.append("0");
			}
		}

		return sBuilder.toString();
	}

	/**
	 * 加盐md5
	 * @param content
	 * @param salt
	 * @return
	 */
	public static String encrypt(String content, String salt) {
		String contentSalt = encrypt(content + salt);
		char[] cs = new char[48];
		for (int i = 0; i < 48; i += 3) {
			cs[i] = contentSalt.charAt(i / 3 * 2);
			char c = salt.charAt(i / 3);
			cs[i + 1] = c;
			cs[i + 2] = contentSalt.charAt(i / 3 * 2 + 1);
		}
		return String.valueOf(cs);
	}
}
